<template>
  <ElDialog v-model="visible" :title="title" :width="width">
    <BreadCrumb :folder-stack="folderStack" @navigate="handleNavigate" />
    <Table ref="tableRef" :columns="tableColumns" :options="tableOptions">
      <template #filename="{ row }">
        <div>
          <ElIcon size="14">
            <Folder />
          </ElIcon>
          <ElLink
            style="margin-left: 10px; font-weight: 400; cursor: pointer"
            @click="openFolder(row)"
            >{{ row.filename }}</ElLink
          >
        </div>
      </template>
    </Table>
    <template #footer>
      <div>
        <ElButton @click="visible = false">取消</ElButton>
        <ElButton type="primary" @click="handleMove"> 移动 </ElButton>
      </div>
    </template>
  </ElDialog>
</template>

<script setup>
import { Table, BreadCrumb } from '@/components'
import { URLS } from '@/constants'
import { watch, ref } from 'vue'
import service from '@/utils/api'
import { PlainMessage } from '@/utils'

const visible = defineModel('modelValue', {
  type: Boolean,
  default: false
})

const { title, width, excludeIds } = defineProps({
  title: {
    type: String,
    default: ''
  },
  width: {
    type: Number,
    default: 600
  },
  excludeIds: {
    type: Array,
    default: () => [],
    required: true
  }
})

const emits = defineEmits(['move'])

const tableOptions = {
  url: URLS.GET_FOLDERS,
  border: false,
  params: {
    excludeIds: excludeIds.join(','),
    parentId: null
  }
}

const tableColumns = [
  {
    key: 'filename',
    align: 'left',
    slot: 'filename'
  }
]

const folderStack = ref([])
const tableRef = ref(null)

watch(
  () => excludeIds,
  newVal => {
    tableOptions.params.excludeIds = newVal.join(',')
  },
  { deep: true }
)

const openFolder = async folder => {
  tableOptions.params.parentId = folder.id

  folderStack.value.push({
    id: folder.id,
    name: folder.filename
  })

  tableRef.value.refreshGrid()
}

const handleNavigate = id => {
  if (id === undefined) {
    tableOptions.params.parentId = null

    folderStack.value = []

    tableRef.value.refreshGrid()
  } else {
    if (id === folderStack.value[folderStack.value.length - 1].id) return

    tableOptions.params.parentId = id

    const index = folderStack.value.findIndex(folder => folder.id === id)
    folderStack.value = folderStack.value.slice(0, index + 1)

    tableRef.value.refreshGrid()
  }
}

const handleMove = async () => {
  await service.post(URLS.MOVE_FILES, {
    fileIds: tableOptions.params.excludeIds.split(',').map(Number),
    targetFolderId: tableOptions.params.parentId
  })

  visible.value = false
  emits('move')
}
</script>

<style scoped>
:deep(.el-icon) {
  vertical-align: middle;
}
</style>
